package cn.wolfcode.luowowo.website.intercepter;


import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
public class LoginIntercepter implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 判断一下这个处理器是否是controller方法,有可能是静态资源的.
        /**
         *
         * 当登陆完去到其他页面的时候
         */
        UserInfo userInfo = null;

        if (handler instanceof HandlerMethod){
            HandlerMethod method = ((HandlerMethod) handler);
            String key = CookieUtil.getToken(request, response);
            //从redis中通过token值获取用户对象
            userInfo = userInfoRedisService.getUserInfoByToken(key);
            //如果方法上贴有这个注解,判断他是否已经登录
            if (method.hasMethodAnnotation(RequireLogin.class)){
                //从浏览器中获取cookie中的token值
                if (userInfo==null){
                    response.sendRedirect("login.html");
                    return false;
                }
            }
        }

        //如果有在这里共享进入每一个方法都有用户对象
        if(userInfo!=null){
            request.getSession().setAttribute("userInfo",userInfo);
        }
        //从redis中通过token值获取用户对象
        return true;
    }
}
